<template lang="pug">
  .app-container.product-created
    h1.page-title 产品配置
    .main
      el-breadcrumb(
        class="title"
        separator-class="el-icon-arrow-right")
        el-breadcrumb-item(:to="{ path: '/product' }") 产品列表
        el-breadcrumb-item 添加产品
      .table-wrapper
        el-scrollbar(style="height:100%")
          el-form(
            ref="form"
            :rules="rules"
            :model="form"
            label-position="top"
            label-width="80px")
            el-row
              el-col(:xs="18" :sm="16" :md="14")
                el-form-item(prop="productName")
                  span(slot="label") 产品名称
                    //- transition(:name="el-zoom-in-top") 'element-ui/packages/theme-chalk/src/common/transition'
                    el-popover(
                      placement="top-start"
                      width="260"
                      trigger="hover"
                      offset="10"
                      transition="el-zoom-in-top")
                      .el-popover--content 选择的品类定义了该类设备的物模型，您可以直接选择并快速完成产品的功能定义，您也可以根据实际需要进行扩展和自定义完成产品的功能定义。品类的物模型标准来源于 ICA 联盟。
                      el-button(class="question" type="text" slot="reference")
                        i.el-icon-question
                  el-input(v-model="form.productName" placeholder="请输入您的产品名称")
            el-row
              el-col(:xs="18" :sm="16" :md="14")
                el-form-item(label="所属品类" prop="categoryKey")
                  el-row
                    el-radio-group(v-model="form.categoryKey")
                      el-radio(:label="1") 标准品类
                      el-radio(:label="2") 自定义品类
                  el-row(v-show="form.categoryKey===1")
                    el-input(
                      class="category"
                      placeholder="请选择标准品类"
                      suffix-icon="el-icon-arrow-down"
                      readonly=true
                      v-model="form.category.label"
                      @click.native="onShowCategoryDialog")
            el-row
              el-col(:xs="18" :sm="16" :md="14")
                el-form-item(label="节点类型" prop="nodeType")
                  el-button(
                    v-for="(item,index) in nodeTypes"
                    :key="index"
                    :class="form.nodeTypeValue===index? 'current':''"
                    plain
                    @click="onChangeButton(index)")
                    el-image(:src="item.imgSrc")
                    .text {{ item.text }}
            el-row
              el-col(:xs="18" :sm="16" :md="14")
                el-form-item(label="所属系统" prop="value1")
                  el-select(
                    v-model="form.value1"
                    placeholder="所属系统"
                    style="width:100%")
                    el-option(
                      v-for="item in options1"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value")
            el-row
              el-col(:xs="18" :sm="16" :md="14")
                el-form-item(label="协议类型" prop="value2")
                  el-select(
                    v-model="form.value2"
                    placeholder="节点类型"
                    style="width:100%")
                    el-option(
                      v-for="item in options2"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value")
            .flex-row
              .flex-item
                el-form-item(label="产品图标" prop="")
                  .flex-row.align--end
                    .flex-item
                      .img-box
                        el-image(:src="productIcon" fit="scale-down" class="img-box--inner")
                    .flex-item
                      el-upload(
                        action=""
                        :show-file-list="false"
                        :on-change="onChangeProductIcon"
                        :http-request="uploadImage")
                        el-button(size="small" type="primary") 点击上传
              .flex-item
                el-form-item(label="产品图片" prop="")
                  .flex-row.align--end
                    .flex-item
                      .img-box
                        el-image(:src="productDefaultImage" fit="scale-down" class="img-box--inner")
                    .flex-item
                      el-upload(action=""
                        :show-file-list="false"
                        :on-change="onChangeProductImage"
                        :http-request="uploadImage")
                        el-button(size="small" type="primary") 点击上传
            el-row
              el-col(:xs="18" :sm="16" :md="14")
                div 更多信息
                el-form-item(label="产品描述" prop="")
                  el-input(
                    type="textarea"
                    placeholder="请输入内容"
                    v-model="form.textarea"
                    maxlength="100"
                    rows="4"
                    show-word-limit)

            el-row
              el-col(:xs="18" :sm="16" :md="14")
                el-form-item(size="large")
                  el-button(type="primary" @click="onSubmit('form')") 保存
                  el-button(type="info" plain @click="resetForm('form')") 取消

    el-dialog(
      custom-class="category-dialog"
      title="选择品类"
      top="0"
      :visible.sync="dialogVisible" :modal-append-to-body="true" :append-to-body="true")
      //- el-scrollbar(style="height:100%")
      .dialog-content--wrapper
        .search-bar
          el-form(
            ref="filterForm"
            :model="filterForm")
            el-select(
              v-model="filterForm.categoryId"
              placeholder="节点类型"
              style="width:100%")
              el-option(
                v-for="item in rootCategories"
                :key="item.Id"
                :label="item.CategoryName"
                :value="item.Id")
        .table-wrapper
          el-table(
            style="width: 100%"
            height="100%"
            :data="paginationCategoies")
            el-table-column(property="CategoryName" label="品类名称")
            el-table-column(property="Id" label="Id")
            el-table-column(width="100")
              template(slot="header" slot-scope="scope")
                .label(style="text-align:center") 操作
              template(slot-scope="scope")
                div(class="button-wrapper")
                  el-button(
                    size="mini"
                    type="text"
                    :disabled="form.category.value === scope.row.Id"
                    @click="onSelectCategory(scope.$index, scope.row)") {{form.category.value === scope.row.Id ? '已选择' : '选择'}}
        .pagination-wrapper
          el-pagination(
            background
            :pager-count="pagerCount"
            :current-page.sync="CurrentPage"
            :page-size.sync="pageSize"
            layout="total,prev, pager, next"
            :total="filterCategiryTotal")
      div(slot="footer")
        el-button(@click="onHideCategoryDialogClose") 关闭
</template>

<script>
import nodeTypeImage1 from '@/assets/product/create/1186.png'
import nodeTypeImage2 from '@/assets/product/create/1193.png'
import nodeTypeImage3 from '@/assets/product/create/1198.png'
import productIcon from '@/assets/product/create/4@2x.png'
import productDefaultImage from '@/assets/product/create/devimg-default@2x.png'
import { ListAllCategoryConsole } from './mock'
import { pagination } from './util'

export default {
  name: 'CreateProduct',
  data () {
    return {
      // 节点类型
      nodeTypes: [
        {
          imgSrc: nodeTypeImage1,
          text: '直连设备'
        },
        {
          imgSrc: nodeTypeImage2,
          text: '直连设备'
        },
        {
          imgSrc: nodeTypeImage3,
          text: '直连设备'
        }
      ],
      // 所属系统
      options1: [
        {
          value: 0,
          label: '全部系统'
        },
        {
          value: 1,
          label: '供水'
        },
        {
          value: 2,
          label: '给排水'
        },
        {
          value: 3,
          label: '供配电'
        },
        {
          value: 4,
          label: '暖通空调'
        },

        {
          value: 5,
          label: '消防'
        },
        {
          value: 6,
          label: '中央空调'
        },
        {
          value: 7,
          label: '排风机设备'
        },
        {
          value: 8,
          label: '空调机组设备'
        },
        {
          value: 9,
          label: '冷冻水系统公共设备'
        },
        {
          value: 10,
          label: '新风机组设备'
        },
        {
          value: 11,
          label: '环境'
        },
        {
          value: 12,
          label: '网络摄像头'
        },
        {
          value: 13,
          label: '电梯'
        },
        {
          value: 14,
          label: '能源'
        },

        {
          value: 15,
          label: '其他'
        }
      ],
      // 协议类型
      options2: [
        {
          value: 0,
          label: '全部产品'
        },
        {
          value: 1,
          label: '默认产品'
        },
        {
          value: 2,
          label: '阿里云产品'
        },
        {
          value: 3,
          label: '电信产品'
        },
        {
          value: 4,
          label: '阿里云网关'
        },

        {
          value: 5,
          label: '终端设备'
        },
        {
          value: 6,
          label: '普通网关'
        }
      ],
      productIcon: productIcon,
      productDefaultImage: productDefaultImage,
      // 表单 添加产品
      form: {
        categoryKey: 1,
        category: {
          label: '',
          value: ''
        },
        nodeTypeValue: 0,
        textarea: ''
      },
      // 表单效验
      rules: {
        productName: [
          { required: true, message: '请输入您的产品名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        categoryKey: [
          { required: true, message: '请选择活动区域', trigger: 'change' }
        ],
        nodeType: [{ required: true }],
        value1: [{ required: true }],
        value2: [{ required: true }]
      },
      /*
        标准品类选择器部分
      */
      // 标准品类选择器弹框显示控制
      dialogVisible: false,
      // 条件筛选
      filterForm: {
        categoryId: 0
      },
      // 分类列表源
      categoryList: [],
      // 分类列表 过滤后
      filterCategiryList: [],
      // 分页配置 页码个数
      pagerCount: 5,
      // 分页配置 当前页
      CurrentPage: 1,
      // 分页配置 每页显示条数
      pageSize: 10,
      localUrl: ''
    }
  },
  computed: {
    /**
     * 根分类
     */
    rootCategories () {
      const catelist = this.categoryList
        .filter(item => item.SuperId === 0)
        .map(item => {
          return {
            ...item,
            site: item.CategoryName
          }
        })
      return [
        {
          SuperId: 0,
          CategoryKey: 'AllCategory',
          CategoryName: '全部领域',
          Id: 0,
          site: ''
        },
        ...catelist
      ]
    },

    /**
     * 过滤后的总条数
     */
    filterCategiryTotal () {
      return this.filterCategiryList.length
    },
    /**
     * 分页后的数据列表
     */
    paginationCategoies () {
      return pagination(
        this.pageSize,
        this.CurrentPage,
        this.filterCategiryList
      )
    }
  },
  watch: {
    /**
     * 监听条件筛选
     */
    filterForm: {
      handler (newName, oldName) {
        this.changeFilterList()
      },
      // immediate: true,
      deep: true
    }
  },
  created () {
    this.categoryList = ListAllCategoryConsole.data.Data.CategoryInfo
    this.getTreeList(this.rootCategories[0])
  },
  methods: {
    onChangeButton (index) {
      this.form.nodeTypeValue = index
    },
    onSubmit (form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          alert('submit!')
        } else {
          console.log('error submit!!')
          return false
        }
      })
      console.log('submit!', this.form)
    },
    resetForm (form) {
      this.$refs[form].resetFields()
    },
    onShowCategoryDialog () {
      this.dialogVisible = true
    },
    onHideCategoryDialogClose () {
      this.dialogVisible = false
    },

    getTreeList (superItem) {
      if (!superItem) {
        return
      }
      var children = this.categoryList.filter(
        item => item.SuperId === superItem.Id
      )
      if (children.length > 0) {
        children.forEach(item => {
          const returnItem = {
            SuperId: item.SuperId,
            CategoryKey: item.CategoryKey,
            CategoryName: item.CategoryName,
            Id: item.Id,
            site: superItem.Id === 0 ? `${item.CategoryName}` : `${superItem.site || superItem.CategoryName} / ${item.CategoryName}`
          }
          this.filterCategiryList.push(returnItem)
          this.getTreeList(returnItem)
        })
      }
    },

    changeFilterList () {
      this.CurrentPage = 1
      this.filterCategiryList = []
      let superItem = this.categoryList.find(
        item => item.Id === this.filterForm.categoryId
      )
      if (this.filterForm.categoryId === 0) {
        superItem = this.rootCategories[0]
      }
      this.getTreeList(superItem)
    },
    onSelectCategory (index, item) {
      this.form.category.label = item.site
      this.form.category.value = item.Id
      this.onHideCategoryDialogClose()
    },
    onChangeProductIcon (file, fileList) {
      // 转换后的地址为 blob:http://xxx/7bf54338-74bb-47b9-9a7f-7a7093c716b5
      this.productIcon = this.getLocalImageUrl(file)
      // this.fileList = fileList.slice(-3)
    },
    onChangeProductImage (file, fileList) {
      this.productDefaultImage = this.getLocalImageUrl(file)
    },
    getLocalImageUrl (file) {
      // 获取上传图片的本地URL，用于上传前的本地预览
      var URL = null
      if (window.createObjectURL !== undefined) {
        // basic
        URL = window.createObjectURL(file.raw)
      } else if (window.URL !== undefined) {
        // mozilla(firefox)
        URL = window.URL.createObjectURL(file.raw)
      } else if (window.webkitURL !== undefined) {
        // webkit or chrome
        URL = window.webkitURL.createObjectURL(file.raw)
      }

      return URL
    },
    uploadImage (params) {
      //* 1. 图片处理
      const { file } = params
      const fileType = file.type // 获取文件类型
      const isImage = fileType.indexOf('image') !== -1 // 判断是否是图片类型
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        // 判断大小
        this.$message.error('上传图片的大小不能超过 2MB!')
        return Promise.reject(new Error('上传图片的大小不能超过 2MB!'))
      }
      if (!isImage) {
        // 文件格式
        this.$message.error('请选择图片文件！')
        return Promise.reject(new Error('请选择图片文件！'))
      }
      //* 2. 图片上传
      const formData = new FormData()
      formData.append('file', file)
      console.log(FormData)
      // TODO
    }
  }
}
</script>

<style lang="stylus" scoped>
$lineheight = (20 / 14)
.app-container
  position absolute
  top 0
  right 0
  bottom 0
  left 0
  background-color #f2f2f7
  padding 20px
  display flex
  flex-direction column
.page-title
  margin-top 0
  color #000
  font-size 24px
  font-weight normal
  flex-shrink 0
.main
  flex 1
  overflow hidden
  background-color #ffffff
  display flex
  flex-direction column
.title
  margin 16px 0
  display flex
  align-items center
  color #000
  font-size 20px
  font-weight normal
  &::before
    content ''
    display inline-block
    width 7px
    height 22px
    margin-right 20px
    background-color #017eff
.table-wrapper
  margin 20px
  flex 1
  overflow hidden
.el-popover--content
  font-size 12px
  line-height $lineheight
.question
  margin-left 4px
  cursor help
.button-wrapper
  display flex
  justify-content center
.flex-row
  display flex
  &.align--end
    align-items:flex-end
  .flex-item
    margin-right 20px
.img-box
  width 100px
  height 100px
  background-color #f5f5f5
  vertical-align top
  display flex
  align-items center
  justify-content center
  &--inner
    max-width 100%
    max-height 100%
    vertical-align top
</style>

<style lang="stylus">
.category-dialog
  position absolute
  top 0
  right 0
  bottom 0
  margin 0
  width 422px
  display flex
  flex-direction column
  .el-dialog
    &__header, &__footer
      flex-shrink 0
    &__footer
      text-align left
    &__body
      border-top 1px solid #EBEEF5
      border-bottom 1px solid #EBEEF5
      flex 1
      overflow hidden
  .dialog-content--wrapper
    display flex
    flex-direction column
    height 100%
  .table-wrapper
    flex 1
    overflow hidden
    margin 20px 0
  .pagination-wrapper
    display flex
    justify-content flex-end
    .el-pagination.is-background .btn-next, .el-pagination.is-background .btn-prev, .el-pagination.is-background .el-pager li
      margin 0 1px
.el-scrollbar__wrap
  overflow-x hidden
.product-created
  .el-button.current
    background #FFF
    border-color #409EFF
    color #409EFF
  .category input[readonly='readonly']
    cursor pointer
  .title .is-link
    font-weight normal
</style>
